package poc.spring.services;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.xml.namespace.NamespaceContext;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import poc.bcsoi.utils.BcsoiQueryParamUtils;
import poc.spring.interfaces.IBcsoiCacheService;
import poc.spring.model.BcsoiCacheQueryParams;

@Repository("iBcsoiCacheService")
@Transactional(readOnly = true)
public class BcsoiCacheServiceJpa implements IBcsoiCacheService {

	private EntityManager entityManager;
	private Logger log = Logger.getLogger(this.getClass());

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}


	public BcsoiCacheQueryParams getById(int id) {
		return entityManager.find(BcsoiCacheQueryParams.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<BcsoiCacheQueryParams> getAll(String adapterName) {		
		Query query = entityManager.createNamedQuery("Cache.findAll")
			.setParameter("adapterName", adapterName);
		
		List<BcsoiCacheQueryParams> bcsoiParams = null;
		bcsoiParams = query.getResultList();
		
		return bcsoiParams;
	}

	
	public boolean save(BcsoiCacheQueryParams bcsoiQP) {
		log.info("\n****************\n........... Persisting Object ..............\n***********");
		entityManager.persist(bcsoiQP);
		entityManager.flush();
		
		return true;
	}
	
	public boolean save(String xmlSrc, NamespaceContext context) {		
		BcsoiCacheQueryParams bcsoiQP = BcsoiQueryParamUtils.createBcsoiQueryParam(xmlSrc, context);
		save(bcsoiQP);		
		
		return true;
	}
	
	
	public boolean delete(String adapterName) {
		Query query = entityManager.createNamedQuery("Cache.deleteAllByAdapter")
			.setParameter("adapterName", adapterName);
	
		// if this fails an exception will be thrown 
		int rowCount = query.executeUpdate();		
		log.info("\n***************\nDELETE QUERY EXECUTED\n\tRows affected: " + rowCount +"\n*************");
	
		return true;
	}

	public boolean delete(BcsoiCacheQueryParams bcsoiQP) {
		bcsoiQP = entityManager.getReference(BcsoiCacheQueryParams.class, bcsoiQP.getId());
		if (bcsoiQP == null) {
			return false;			
		}
		entityManager.remove(bcsoiQP);
		entityManager.flush();
		
		return true;
	}

	
	public boolean update(BcsoiCacheQueryParams bcsoiQP) {
		entityManager.merge(bcsoiQP);
		entityManager.flush();
		
		return true;
	}
	
	public int count(String adapterName) {
		
		
		return 2;
	}

}
